package com.huo.qq.webqq;

import java.net.URLEncoder;

import javax.swing.JLabel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.huo.http.HttpService;
import com.huo.common.StringUtil;
import com.huo.qq.common.GlobalURL;
import com.huo.qq.common.QQUtils;
import com.huo.qq.common.VerifyCode;

/**
 * <p>Description: </p>
 * @author Huoyan
 * @version 1.0
 * <p>Copyright 2011</p>
 */

public class WebQQClient extends HttpService {

	private final Log log = LogFactory.getLog(this.getClass());
	
	private String qq = null;
	private String pwd = null;
	
	@SuppressWarnings("unused")
	private boolean loginState = false;  //登录状态
	private long clientid = 18662986;
	private String psessionid = "";
	
	private String ptwebqq;
	private String vfwebqq = null;
	
	@SuppressWarnings("unused")
	private String skey = null;
	
	public WebQQClient(String qq, String pwd){
		this.qq = qq;
		this.pwd = pwd;
		this.clientid = QQUtils.createClientID();
		//设置请求头中参数refer
		setRefer(GlobalURL.REFER);
	}
	
	/**
	 * webQQ接口登录
	 */
	@SuppressWarnings("deprecation")
	public void login(String verifyCode){
		loginState = false; //当前登录状态
		try {
			if(qq == null || pwd == null){
				log.error("使用qq: " + qq + "登录时，用户名或密码为空，登录失败");
			}else{
				StringBuffer loginUrl = new StringBuffer(GlobalURL.LOGIN_URL);
				//登录步骤2，发送登录信息
				loginUrl.append("u=").append(qq)
					.append("&p=").append(QQUtils.encodePass(pwd, verifyCode, "\\x00\\x00\\x00\\x00\\x85\\x17\\xb8\\x17"))
					.append("&verifycode=").append(verifyCode)
					.append("&webqq_type=10").append("&remember_uin=1")
					.append("&login2qq=1").append("&aid=1003903")
					.append("&u1=http%3A%2F%2Fweb.qq.com%2Floginproxy.html%3Flogin2qq%3D1%26webqq_type%3D10")
					.append("&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=4-11-25737&mibao_css=m_webqq&t=1&g=1");
				//发送请求-登录
				log.info(loginUrl.toString());
				String res = getReturnStr(loginUrl.toString());
				log.info(res);
				//res返回结果webqq2.0
				// ptuiCB('0','0','http://web2.qq.com/loginproxy.html?strong=true','0','登录成功！');
				// ptuiCB('3','0','','0','您输入的帐号或者密码不正确，请重新输入。');
				// ptuiCB('4','0','','0','您输入的验证码有误，请重试。');
				// ptuiCB('7','0','','0','很遗憾，网络连接出现异常，请您稍后再试。(688916544)');
				// ptuiCB('4','3','','0','登录失败，请重试!*', '[QQ号码]');
				//res返回结果webqq3.0
				//ptuiCB('0','0','http://web.qq.com/loginproxy.html?login2qq=1&webqq_type=10','0','登录成功！', '[昵称]');
				if (StringUtil.exist("登录成功！", res)) {
					log.info(">>正在登录..");
				} else {
					log.info("一登录失败");
					//System.out.println(res.indexOf("3",8)); //待完善
					return;
				}
				
				// 从cookie中提取ptwebqq,skey
				ptwebqq = getCookie("ptwebqq");
				skey = getCookie("skey");
				
				//登录步骤3, 再次登陆，只有这次登陆，才算真正登陆qq，这个时候，如果你qq已经登陆，会把你的qq踢下线，而且此次登陆才算上线。
				String channelLoginUrl = "http://d.web2.qq.com/channel/login2";
				String content = "{\"status\":\"online\",\"ptwebqq\":\"" + ptwebqq
						+ "\",\"passwd_sig\":\"\",\"clientid\":\"" + clientid 
						+ "\",\"psessionid\":null}&clientid=" + clientid + "&psessionid=";
				content = "r=" + URLEncoder.encode(content);// urlencode转码，拼装post数据
				//发送请求
				res = postReturnStr(channelLoginUrl, content);
				
				// 这次登陆基本上不会发生什么问题
				// 下面提取很重要的2个数据psessionid ,vwebqq，通用采用正则表达式,虽然结果是个json
				vfwebqq = StringUtil.findPattern("\"vfwebqq\":\"(\\w+)\"", res);
				psessionid = StringUtil.findPattern("\"psessionid\":\"(\\w+)\"", res);
				
				log.info(">>登录成功\n vfwebqq="+vfwebqq + ", psessionid="+psessionid);
				loginState = true; //当前登录状态
				// 到此，登陆就算完成了，后面可以调用发送qq信息等接口了
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			shutdown();
		}
	}
	
	/**
	 * 获取十六进制QQ号,如"\\x00\\x00\\x00\\x00\\x85\\x17\\xb8\\x17"
	 * @param qq
	 * @return
	 */
	public String getHexQQNumber(String qq){
		String url = GlobalURL.hexQQNumber + qq;
		String res = getReturnStr(url);
		return res.substring(res.lastIndexOf(",'")+2, res.lastIndexOf("')"));
	}
	
	public static void main(String[] args) {
		//需要验证码QQ2508786110,2351221103, 2536565342
		//不需要2232924183
		WebQQClient c = new WebQQClient("2232924183", "asdf1234");
		//获得QQ号码16进制表示
		//System.out.println(c.getHexQQNumber("2232924183"));
		//获得验证码
		String vc = new VerifyCode(c.getClient()).getVerifyCode("2232924183", new JLabel());
		//qq登陆
		c.login(vc);
	}
}
